package com.hgd.security.evp.biz.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.hgd.security.evp.auth.interceptor.UserAuthRestInterceptor;
import com.hgd.security.evp.biz.interceptor.NetAddressInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * @author By 尚
 * @date 2019/3/28 23:47
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    private NetAddressInterceptor netAddressInterceptor;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter=new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig=new FastJsonConfig();

        fastJsonConfig.setSerializerFeatures(
            SerializerFeature.WriteNullListAsEmpty,//List字段如果为null,输出为[],而非null
            SerializerFeature.WriteNullStringAsEmpty,//字符类型字段如果为null,输出为"",而非null
            SerializerFeature.DisableCircularReferenceDetect, //消除对同一对象循环引用的问题，默认为false（如果不配置有可能会进入死循环）
            SerializerFeature.WriteMapNullValue,//是否输出值为null的字段,默认为false。
            SerializerFeature.WriteDateUseDateFormat// 定义输出日期格式
        );

        // 处理中文乱码
        List<MediaType> fastMediaTypes=new ArrayList<MediaType>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);

        converters.add(fastJsonHttpMessageConverter);

        super.configureMessageConverters(converters);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new UserAuthRestInterceptor());
        registry.addInterceptor(netAddressInterceptor);
        super.addInterceptors(registry);
    }
}
